package core.net;

import core.buffer.BufferManager;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.function.Consumer;

public class TCPClient {

    private Connection _connection;
    private BufferManager _bufferManager;
    private InetSocketAddress _address;
    private NetConfig _config;
    private Consumer<Connection> _connectedHandler;
    public void connectedHandler(Consumer<Connection> handler){
        _connectedHandler = handler;
    }
    public TCPClient(String host, int port, NetConfig config) {
        _address = new InetSocketAddress(host, port);
        _bufferManager = new BufferManager();
        _config = config;
        _connectedHandler = this::connected;
    }

    private void connected(Connection connection) {
        _connection.disconnectHandler(this::disconnected);
        _connection.open();
    }
    private void disconnected(Connection connection) {

    }

    public void open() {
        try {
            Socket socket = new Socket();
            socket.setSoTimeout(_config.ReceiveTimeout());
            socket.connect(_address, _config.ConnectTimeout());
            _connection = new Connection(socket, _bufferManager, _config);
            _connectedHandler.accept(_connection);
        } catch (IOException e) {
            System.out.println(e.getMessage());
            close();
        }
    }

    public void close() {
        if (_connection != null) _connection.close();
    }

}
